<template>
  <div>
  <el-upload  v-if="!isImage"
         action="' '"
          :limit="10"
          show-file-list
          :auto-upload="false"
          :disabled="disabled"
          :on-change="change"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :file-list="fileList"
          accept=".gif, .png, .jpg, .pdf, .doc, .docx"
          multiple
      >
    <el-button v-if="!disabled" plain icon="el-icon-upload2">上传文件</el-button>
    <div v-if="!disabled" slot="tip" class="el-upload__tip">{{description}}</div>
  </el-upload>
  <el-upload v-if="isImage" :class="{hide:hideUpload}"
          action="' '"
          list-type="picture-card"
          :limit="4"
          show-file-list
          accept=".gif, .png, .jpg"
          :auto-upload="false"
          :disabled="disabled"
          :on-change="change"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :file-list="fileList"
          multiple
        >
          <i class="el-icon-plus">图片</i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible" v-if="isImage" append-to-body>
              <img width="100%" :src="dialogImageUrl" alt="" />
        </el-dialog>

        <el-dialog :visible.sync="isPreview" title="文档预览"  append-to-body style="width: 1750px;">
                <div class="container">
                  <div v-show="loading" class="well loading">正在加载中，请耐心等待...</div>
                  <div v-show="!loading" class="well" ref="output"></div>
                </div>
               <div style="margin: 30px;text-align: center;">
               <el-button @click="closePreview">关闭</el-button><el-button @click="download">下载</el-button>
               </div>
        </el-dialog>
  </div>
</template>
<script>
import { getExtend, readBuffer, render } from '@/components/FileViewer/util';
import { parse } from 'qs';
import axios from 'axios';

import { uploadImage } from "@/api/common";
export default {
  name: "uploadCom",
  data() {
    return {
      choosedFile:{},
      isPreview:false,
      host:process.env.VUE_APP_PROXY,
      dataList: [],
      hideUpload:false,
      // 加载状态跟踪
      loading: false,
      //附件集合
      fileList: [],
      dialogVisible: false,
      dialogImageUrl: "",
      // 表单参数
      form: {},
      // 表单校验
      rules: {}
    };
  },
  props:{
    userFileList:Array,
    description:String,
    isImage:Boolean,
    disabled:Boolean,
  },
  watch:{
    userFileList:function(newVal, oldVal){
       this.setFileList(newVal);
       this.$forceUpdate();
    },
  },
  created() {
   this.hideUpload = this.disabled;
   // console.log('hideUpload='+this.hideUpload)
   this.setFileList(this.$props.userFileList);
   // 允许使用预留的消息机制发送二进制数据，必须在url后添加?name=xxx.xxx&from=xxx
   const { from, name } = parse(location.search.substr(1))
   if (from) {
     window.addEventListener('message', event => {
       const { origin, data: blob } = event
       if (origin === from && blob instanceof Blob) {
         // 构造响应，自动渲染
         const file = new File([ blob ], name, {});
         this.hidden = true;
         this.handleChange({ target: { files: [ file ] } });
       }
     })
   }
  },
  methods: {
    closePreview(){
      this.isPreview = false;
    },
    download(instanceId){
      if(!this.choosedFile.url){
        this.msgError('本机文件，不用下载');
        return;
      }
     window.open(this.choosedFile.url);
    },
    setFileList(files){
      //console.log('set files='+JSON.stringify(files));
      //如果刚保存不做更新
      if(!files){
        files = [];
      }
      for(var i=0;i<files.length;i++){
        if(!files[i].fileId){
          return;
        }
      }
      this.fileList = [];
      this.dataList = [];
      this.form.images = files;
      files.forEach(item =>{
        if(item.fileId>0){
          this.fileList.push({
            id: item.fileId,
            name:item.fileName,
            url:this.host+'/labdata/labFile/image?fileId='+item.fileId,
          });
        }else{
          this.fileList.push(item);
        }
        //console.log('fileUrl='+this.fileList[this.fileList.length -1].url);
      } );
      if(this.isImage&&files.length>=4){
        this.hideUpload = true;
      }
    },

    //附件展示
    handlePictureCardPreview(file) {
     if(this.isImage){
         this.dialogImageUrl = file.url;
         this.dialogVisible = true;
       }else{
          //window.location.href = file.url;
          //console.log(JSON.stringify(file));
          this.choosedFile = file;
          this.isPreview = true;
          if(file.url){
             this.gotoView( file.url,file.name);
          }else{
            const previewFile = new File([ file.raw ], file.name, {});
            this.handleChange({ target: { files: [ previewFile ] } });
          }
 
       }
    },
    doSubmit() {
      const formData = new FormData();
      if(!this.form.images) this.form.images = [];
       //console.log('dataList:'+JSON.stringify(this.dataList));
       let dataLength = this.form.images.length;
       if (this.dataList.length>0) {
         this.dataList.forEach((item, index) => {
           formData.append('file', item);
         });
       }
       if(this.dataList.length>0){
           uploadImage(formData).then(response=>{
              //console.log('upload response:'+JSON.stringify(response));
              if(response && response.fileName){
                for(let i=0;i<response.fileName.length; i++){
                  let item = this.dataList[i];
                  this.form.images.push({
                    fileName: item.name,
                    fileSize:item.size,
                    filePath:response.fileName[i],
                  });
                }
                //上传完之后清空数据，防止重复上传
                this.dataList = [];
                if(this.description == "backList"){
                   this.$emit("handSubmitData", this.form.images)
                }else{
                  this.$emit("submitData", this.form.images)
                }
              }
           });
         }else{
           if(this.description == "backList"){
                this.$emit("handSubmitData", this.form.images)
            }else{
              this.$emit("submitData", this.form.images)
            }
         }
     },
    //附件改变
     change(file, fileList) {
       var arr = [];
       const type = file.name.substring(file.name.lastIndexOf('.'));
       if(this.$props.isImage){
         if(!['.gif', '.png', '.jpg'].includes(type)){
           this.msgError('图片上传只支持.gif, .png, .jpg扩展名的文件.');
           fileList.splice(fileList.length - 1, 1);
           return;
         }
       }else{
         if(!['.gif', '.png', '.jpg', '.pdf', '.doc', '.docx'].includes(type)){
           this.msgError('文件上传只支持.gif, .png, .jpg, .pdf, .doc, .docx扩展名的文件.');
           fileList.splice(fileList.length - 1, 1);
           return;
         }
       }
       fileList.forEach((item) => {
         if(item.status=='ready')
         arr.push(item.raw);
       });
       if(this.isImage&&fileList.length>=4){
         this.hideUpload = true;
       }
       this.dataList = arr;
       this.$forceUpdate();
     },
     //附件删除
     handleRemove(file, fileList){
       if(file.id){
         this.form.images.forEach(item=>{
           if(item.fileId ==file.id){
             item.isDelete = 1;
           }
         })
       }
       this.change(file, fileList);
     },
     // 从url加载
     gotoView(myUrl, fileName) {
       this.url = myUrl
       this.filename = fileName;
       this.loadFromUrl()
     },
     // 从url加载
     loadFromUrl() {
       this.loading = true;
       // 要预览的文件地址
       const { url } = this;
       console.log(url)
      // const filename = url.substr(url.lastIndexOf('/') + 1);
       // 拼接iframe请求url
       axios({
         url,
         method: 'get',
         responseType: 'blob',
       }).then(({ data }) => {
         if (!data) {
           console.error('文件下载失败');
         }
         const file = new File([ data ], this.filename, {});
         this.handleChange({ target: { files: [ file ] } });
       }).finally(() => {
         this.loading = false;
       })
     },
     async handleChange(e) {
       this.loading = true;
       try {
         const [ file ] = e.target.files;
         this.filename = file.name && decodeURIComponent(file.name) || '';
         const arrayBuffer = await readBuffer(file);
         this.loading = false
         this.last = await this.displayResult(arrayBuffer, file)
       } catch (e) {
         console.error(e)
       } finally {
         this.loading = false
       }
     },
     displayResult(buffer, file) {
       // 取得文件名
       const { name } = file;
       // 取得扩展名
       const extend = getExtend(name);
       // 输出目的地
       const { output } = this.$refs;
       // 生成新的dom
       const node = document.createElement('div');
       // 添加孩子，防止vue实例替换dom元素
       if (this.last) {
         output.removeChild(this.last.$el);
         this.last.$destroy();
       }
       const child = output.appendChild(node);
       // 调用渲染方法进行渲染
       return new Promise((resolve, reject) => render(buffer, extend, child)
           .then(resolve).catch(reject));
     }
  }
};
</script>
<style type="text/css" lang="scss" scoped>
  .el-button.active{
    text-decoration: underline;
    color: #0000ee;
  }
  .hide {
    /deep/.el-upload--picture-card {
      display: none;
    }
  }

  .hidden .well {
    height: 400px;
  }

  .well {
    display: block;
    background-color: #f2f2f2;
    border: 1px solid #ccc;
    margin: 5px;
    width: calc(100% - 12px);
    height: 400px;
    overflow: auto;
  }

  .loading {
    text-align: center;
    padding-top: 50px;
  }

  .messages .warning {
    color: #cc6600;
  }
  </style>

  <style>
  .pptx-wrapper {
    max-width: 1000px;
    margin: 0 auto;
  }
</style>
